# -*- coding: utf-8 -*-
import requests
import pygal
import webbrowser
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS

filename = 'Key.txt'


def get_the_key(file_name):
    with open(file_name) as file_object:
        appkey = file_object.readline()
        return appkey


Appkey = get_the_key(filename)
if Appkey == '':
    print('No Key!')


# 读取+展示指定属性数据 attr_name为待展示属性的名称
def display_chart(city, attr_name, label_name='position_name'):
        if attr_name == 'position_name' or attr_name == 'primary_pollutant' or attr_name == 'quality':
            print('数据类型不支持保存为此格式！')
            return 0
        labels = []
        plot_dicts = []
        url = 'http://www.pm25.in/api/querys/co.json?city=' + city + '&token=' + Appkey
        cache = requests.get(url)  # 存储缓冲数据
        datas = cache.json()
        for repo_dict in datas:
            labels.append(repo_dict[label_name])
            plot_dicts.append(repo_dict[attr_name])

        labels[-1] = '城市平均'
        chart = pygal.Bar(my_config, style=my_style)
        chart.title = attr_name.upper() + ' Data of ' + city.title()
        chart.add('', plot_dicts)
        chart.x_labels = labels
        file_name = str(attr_name.upper() + ' Data of ' + city.title() + '.svg')  # 保存为文件
        chart.render_to_file(file_name)
        webbrowser.open(file_name)


# 定义用于设置的变量my_style my_config
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()


def chart_config():
    # pygal界面设置
    my_config.x_label_rotation = 45
    my_config.show_legend = False
    my_config.title_font_size = 24
    my_config.label_font_size = 14
    my_config.major_label_font_size = 18
    my_config.truncate_label = 45

